package zk.tool.ui;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zk.tool.App;
import zk.tool.ZKClient;
import zk.tool.component.NodeItem;
import zk.tool.handler.*;
import zk.tool.model.ConnectInfo;
import zk.tool.model.TreeItemData;
import zk.tool.util.AlertUtil;
import zk.tool.util.CopyUtil;
import zk.tool.util.StageUtil;
import zk.tool.util.StatUtil;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;


public class AppController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(AppController.class);

    private ZKClient client = null;

    private NodeItem rootTreeNode;

    private TreeItemData selectedItemData;

    @FXML
    private AnchorPane rootPane;

    @FXML
    private TreeView<TreeItemData> treeView;

    @FXML
    private TextArea dataTextArea;

    @FXML
    private TextArea metaInfoTextArea;

    @FXML
    private Label pathLabel;

    @FXML
    private Button copyPathBtn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Tooltip.install(this.copyPathBtn, new Tooltip("拷贝路径"));
    }

    public void connectToZK(ConnectInfo info) throws IOException, InterruptedException {
        this.client = new ZKClient(info.getConnectStr());
        this.client.setAuth(info.isUseAuth());
        this.client.setUser(info.getUser());
        this.client.setPassword(info.getPassword());
        this.client.connect();
    }

    public void initMenu() {
        // 初始化主菜单
        MenuBar menuBar = new MenuBar();
        menuBar.setUseSystemMenuBar(true);
        Menu fileMenu = new Menu("文件");

        MenuItem createConnectionMenu = new MenuItem("新建连接");
        MenuItem exitMenu = new MenuItem("退出");

        createConnectionMenu.setOnAction(event -> {
            this.openConnectWindow();
        });
        exitMenu.setOnAction(event -> Platform.exit());
        fileMenu.getItems().addAll(createConnectionMenu, exitMenu);
        menuBar.getMenus().add(fileMenu);
        rootPane.getChildren().add(menuBar);
    }

    private void openConnectWindow() {
        try {
            Stage stage = StageUtil.createDialogStage(App.primaryStage, "新建连接");
            FXMLLoader connectLoader = StageUtil.loadFxml("connect.fxml");
            GridPane gp = connectLoader.<GridPane>load();
            connectLoader.<ConnectController>getController().setParent(stage);
            Scene scene = new Scene(gp, 600, 150);
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            log.error("open connect form ui error: ", e);
            AlertUtil.exception("打开窗口错误", e);
        }
    }


    public void initNodeTree() {
        // 初始化根节点
        this.rootTreeNode = new NodeItem(new TreeItemData("/", "/"));
        this.rootTreeNode.addEventHandler(TreeItem.branchExpandedEvent(), new TreeItemExpandHandler(this.client));

        // 放入树中
        this.treeView.setRoot(this.rootTreeNode);

        // 给节点树加上单击事件
        this.treeView.addEventHandler(MouseEvent.MOUSE_CLICKED, new TreeClickHandler());
        this.treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        ContextMenu treeContextMenu = new ContextMenu();
        MenuItem refreshMenu = new MenuItem("刷新");
        MenuItem addMenu = new MenuItem("添加子节点");
        MenuItem deleteMenu = new MenuItem("删除节点");
        addMenu.setOnAction(new AddTreeItemClickHandler(treeView, client));
        deleteMenu.setOnAction(new DeleteTreeItemClickHandler(treeView, client));
        refreshMenu.setOnAction(new RefreshTreeItemClickHandler(treeView, client));
        treeContextMenu.getItems().addAll(refreshMenu, addMenu, deleteMenu);
        treeView.setContextMenu(treeContextMenu);
    }

    public void copyInfo() {
        CopyUtil.copyItemData(CopyUtil.Type.INFO, this.selectedItemData);
    }

    public void copyData() {
        CopyUtil.copyItemData(CopyUtil.Type.DATA, this.selectedItemData);
    }

    public void copyPath() {
        CopyUtil.copyItemData(CopyUtil.Type.PATH, this.selectedItemData);
    }

    public void setPathLabel() {
        if (selectedItemData == null) {
            this.pathLabel.setText("请选择节点");
            return;
        }
        this.pathLabel.setText(selectedItemData.getPath());
        Tooltip.install(this.pathLabel, new Tooltip(selectedItemData.getPath()));
    }

    public void setSelectedItemData(TreeItemData selectedItemData) {
        this.selectedItemData = selectedItemData;
        String statJson = StatUtil.formatStatInfo(selectedItemData.getStat());
        
        Platform.runLater(() -> {
            this.setDataTextAreaContent(selectedItemData.getData());
            this.setMetaInfoMessage(statJson);
            this.setPathLabel();
        });
    }

    public void setMetaInfoMessage(String metaInfoMessage) {
        this.metaInfoTextArea.setText(metaInfoMessage);
    }

    public void setDataTextAreaContent(String content) {
        this.dataTextArea.clear();
        this.dataTextArea.setText(content);
    }

    public TreeView<TreeItemData> getTreeView() {
        return treeView;
    }

    public ZKClient getClient() {
        return client;
    }
}
